package com.fy.opengltest;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.fy.opengltest.Car360.MDFlingConfig;
import com.fy.opengltest.Car360.MDPinchConfig;
import com.fy.opengltest.Car360.MDTouchHelper;
import com.fy.opengltest.renderPicture.GLRendererMultiPictureSphere;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class ActivityCar360Sphere extends AppCompatActivity  implements View.OnClickListener{
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            glSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_multi_sphere);
        mVisible = true;
        paramsTextView = (TextView) findViewById(R.id.params);
        glSurfaceView = (GLSurfaceView) findViewById(R.id.gl_surface_view);
        glSurfaceView.setEGLContextClientVersion(2);
        List<Uri> uris = new ArrayList<>();
        uris.add(Uri.fromFile(new File("/storage/emulated/0/vr/car1080/left603x603.png")));
        uris.add(Uri.fromFile(new File("/storage/emulated/0/vr/car1080/right603x603.png")));
        uris.add(Uri.fromFile(new File("/storage/emulated/0/vr/car1080/back603x603.png")));
        uris.add(Uri.fromFile(new File("/storage/emulated/0/vr/car1080/front603x603.png")));
        mRenderer = new GLRendererMultiPictureSphere(this, uris);
        glSurfaceView.setRenderer(mRenderer);
        mdTouchHelper = new MDTouchHelper(this);
        mdTouchHelper.setGestureListener(gestureListener);
        mdTouchHelper.setFlingConfig(new MDFlingConfig());
        mdTouchHelper.setPinchConfig(pinchConfig);
        glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mdTouchHelper.handleTouchEvent(event);
            }
        });

        SparseArray<String> data = new SparseArray<>();
        data.put(0, "Left");
        data.put(1, "Right");
        data.put(2, "Back");
        data.put(3, "Front");
        SpinnerHelper spinnerHelper = SpinnerHelper.with(this)
                .setData(data)
                .setDefault(mSelectItem)
                .setClickHandler(new SpinnerHelper.ClickHandler() {
                    @Override
                    public void onSpinnerClicked(int index, int key, String value) {
                        if (mSelectItem != key) {
                            mSelectItem = key;
                            updateRange(mSelectItem, mSelectType, mSelectParam);
                        }
                    }
                });
        spinnerHelper.init(R.id.control_item);

        data = new SparseArray<>();
        data.put(0, "Camera");
        data.put(1, "Model");
        data.put(2, "Calibrate");
        spinnerHelper = SpinnerHelper.with(this)
                .setDefault(mSelectType)
                .setData(data)
                .setClickHandler(new SpinnerHelper.ClickHandler() {
                    @Override
                    public void onSpinnerClicked(int index, int key, String value) {
                        if (mSelectType == key) {
                            return;
                        }
                        onTypeChange(key);
                        updateRange(mSelectItem, mSelectType, mSelectParam);
                    }
                });
        spinnerHelper.init(R.id.control_type);

        mSpinnerHelper = SpinnerHelper.with(this)
                .setData(getDataByType(mSelectType))
                .setDefault(mSelectParam)
                .setClickHandler(new SpinnerHelper.ClickHandler() {
                    @Override
                    public void onSpinnerClicked(int index, int key, String value) {
                        if (mSelectParam == key) {
                            return;
                        }
                        mSelectParam = key;
                        updateRange(mSelectItem, mSelectType, mSelectParam);
                    }
                });
        mSpinnerHelper.init(R.id.control_param);
        updateText();
        updateRange(mSelectItem, mSelectType, mSelectParam);

        findViewById(R.id.inc_btn).setOnClickListener(this);
        findViewById(R.id.dec_btn).setOnClickListener(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        glSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }


    private GLSurfaceView glSurfaceView;
    private GLRendererMultiPictureSphere mRenderer = null;

    private TextView paramsTextView;

    MDTouchHelper mdTouchHelper;
    SpinnerHelper mSpinnerHelper;
    int mSelectItem;
    int mSelectType = 1;
    int mSelectParam;

    private MDPinchConfig pinchConfig = new MDPinchConfig();

    private SparseArray<String> getDataByType(int type) {
        switch (type) {
            case 0:
                return camera;
            case 1:
                return model;
            case 2:
                return calibrate;
        }
        return null;
    }

    void updateValue(int item, int type, int param, boolean add) {
        float value = mRenderer.getValue(item, type, param);
        float max = 0f;
        float min = 0f;
        switch (type) {
            case 0:
                min = rangeCamera[param][0];
                max = rangeCamera[param][1];
                break;
            case 1:
                min = rangeModel[param][0];
                max = rangeModel[param][1];
                break;
            case 2:
                min = rangeCalibrate[param][0];
                max = rangeCalibrate[param][1];
                break;
        }
        if (add) {
            value += (max - min) / 100f;
        } else {
            value -= (max - min) / 100f;
        }
        if (value < min) {
            value = min;
        } else if (value > max) {
            value = max;
        }
        pinchConfig.setDefaultValue(value);
        pinchConfig.setMax(max);
        pinchConfig.setMin(min);
        pinchConfig.setSensitivity((max - min) / 50f);
        mdTouchHelper.setPinchConfig(pinchConfig);
        Log.d(TAG, " value=" + value + " max=" + max + " min=" + min + " sens=" + ((max - min) / 2f));
    }

    void updateRange(int item, int type, int param) {
        float value = mRenderer.getValue(item, type, param);
        float[][] range = null;
        switch (type) {
            case 0:
                range = rangeCamera;
                break;
            case 1:
                range = rangeModel;
                break;
            case 2:
                range = rangeCalibrate;
                break;
        }
        if (param > range.length){
            param = 0;
        }
        float min = range[param][0];
        float max = range[param][1];
        pinchConfig.setDefaultValue(value);
        pinchConfig.setMax(max);
        pinchConfig.setMin(min);
        pinchConfig.setSensitivity((max - min) / 50f);
        mdTouchHelper.setPinchConfig(pinchConfig);
        Log.d(TAG, " value=" + value + " max=" + max + " min=" + min + " sens=" + ((max - min) / 2f));
    }

    void updateText() {
        paramsTextView.setText(mRenderer.getParams(mSelectItem));
    }

    void onTypeChange(int key) {
        mSelectType = key;
        switch (key) {
            case 0:
                mSpinnerHelper.updateData(camera, R.id.control_param);
                break;
            case 1:
                mSpinnerHelper.updateData(model, R.id.control_param);
                break;
            case 2:
                mSpinnerHelper.updateData(calibrate, R.id.control_param);
                break;
        }
    }

    static SparseArray<String> camera = new SparseArray<>();
    static SparseArray<String> model = new SparseArray<>();
    static SparseArray<String> calibrate = new SparseArray<>();

    static float[][] rangeCamera = {
            {-1000f, 1000f},
            {-1000f, 1000f},
            {-1000f, 1000f},

            {-1f, 1f},
            {-1f, 1f},
            {-1f, 1f},

            {-1f, 1f},
            {-1f, 1f},
            {-1f, 1f},
    };

    static float[][] rangeModel = {
            {-20f, 20f},
            {-20f, 20f},
            {-20f, 60f},

            {0f, 360f},
            {0f, 360f},
            {0f, 360f},

            {0f, 360f},
            {0f, 360f},
            {0f, 360f},
    };

    static float[][] rangeCalibrate = {
            {-1f, 1f},
            {-1f, 1f},
            {-2f, 2f},
            {18f, 500f},
            {90f, 360f}
    };


    static {
        camera.put(0, "eyeX");
        camera.put(1, "eyeY");
        camera.put(2, "eyeZ");
        camera.put(3, "lookX");
        camera.put(4, "lookY");
        camera.put(5, "lookZ");
        camera.put(6, "upX");
        camera.put(7, "upY");
        camera.put(8, "upZ");

        model.put(0, "mX");
        model.put(1, "mY");
        model.put(2, "mZ");
        model.put(3, "mAngleX");
        model.put(4, "mAngleY");
        model.put(5, "mAngleZ");
        model.put(6, "mPitch(x-axis)");
        model.put(7, "mYaw(y-axis)");
        model.put(8, "mRoll(z-axis)");

        calibrate.put(0, "OffsetX");
        calibrate.put(1, "OffsetY");
        calibrate.put(2, "RadiusCal");
        calibrate.put(3, "Radius");
        calibrate.put(4, "DegreeY");
    }

    private static final String TAG = "Car360";
    MDTouchHelper.GestureListener gestureListener = new MDTouchHelper.GestureListener() {

        @Override
        public boolean onDrag(float dis_x, float dis_y) {
//            Log.d(TAG, "onDrag dis_x=" + dis_x + " dis_y=" + dis_y);
            return false;
        }

        @Override
        public boolean onClick(MotionEvent e) {
            View view = findViewById(R.id.control_layout);
            toggle();
            if (view.getVisibility() == View.VISIBLE) {
                view.setVisibility(View.GONE);
            } else {
                view.setVisibility(View.VISIBLE);
            }
            return false;
        }

        @Override
        public boolean onPinch(float dis) {
            Log.d(TAG, "onPinch dis=" + dis);
            mRenderer.onChange(mSelectItem, mSelectType, mSelectParam, dis);
            updateText();
            return false;
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.inc_btn:
                updateValue(mSelectItem, mSelectType, mSelectParam, true);
                break;
            case R.id.dec_btn:
                updateValue(mSelectItem,mSelectType, mSelectParam, false);
                break;
        }
    }
}
